package com.lyz.weixinservice;

import lombok.Data;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.material.WxMpMaterial;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialUploadResult;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
public class WechatController {

    private final WxMpService wxMpService;

    // 依赖注入 WxMpService，工具库提供的微信服务类
    public WechatController(WxMpService wxMpService) {
        this.wxMpService = wxMpService;
    }

    // 获取微信token接口
    @GetMapping("/getAccessToken")
    public String getWechatToken() {
        try {
            return wxMpService.getAccessToken();
        } catch (Exception e) {
            return "获取 Token 失败：" + e.getMessage();
        }
    }

    // 上传永久素材接口
    @PostMapping("/material/upload")
    public ResponseEntity<?> uploadMaterial(
            @RequestParam("file") MultipartFile file,
            @RequestParam("type") String type,
            @RequestParam(value = "title", required = false) String title,
            @RequestParam(value = "introduction", required = false) String introduction) {
        try {
            // 1. 临时保存文件到本地
            File tempFile = File.createTempFile("wx_upload_", file.getOriginalFilename());
            file.transferTo(tempFile);

            WxMpMaterial material = new WxMpMaterial();
            material.setFile(tempFile);
            material.setName(file.getOriginalFilename());

            // 直接给 material 赋值
            if ("video".equalsIgnoreCase(type)) {
                material.setVideoTitle(title);       // 用当前类的 setVideoTitle
                material.setVideoIntroduction(introduction); // 用 setVideoIntroduction
            }

            // 2. 上传到微信素材库
            WxMpMaterialUploadResult result = wxMpService.getMaterialService().materialFileUpload(type, material);

            // 3. 封装返回
            MaterialResponse response = new MaterialResponse();
            response.setMedia_id(result.getMediaId());
            response.setUrl(result.getUrl());
            response.setErrcode(0);
            response.setErrmsg("success");

            // 4. 删除临时文件
            tempFile.delete();

            return ResponseEntity.ok(response);
        } catch (WxErrorException e) {
            MaterialResponse response = new MaterialResponse();
            response.setErrcode(e.getError().getErrorCode());
            response.setErrmsg(e.getError().getErrorMsg());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        } catch (Exception e) {
            MaterialResponse response = new MaterialResponse();
            response.setErrcode(-1);
            response.setErrmsg("系统错误：" + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    // 新增草稿接口 - 接收Coze的请求并转发到微信
    @PostMapping("/draft/add")
    public ResponseEntity<?> addDraft(@RequestBody DraftRequest request) {
        try {
            // 构建微信API请求参数
            Map<String, Object> requestData = new HashMap<>();
            requestData.put("articles", request.getArticles());
            
            // 调用微信API新增草稿
            String result = wxMpService.post("https://api.weixin.qq.com/cgi-bin/draft/add", requestData);
            
            // 解析返回结果
            DraftResponse response = new DraftResponse();
            if (result.contains("media_id")) {
                // 成功情况
                response.setMedia_id(extractMediaId(result));
                response.setErrcode(0);
                response.setErrmsg("success");
                return ResponseEntity.ok(response);
            } else {
                // 错误情况
                response.setErrcode(-1);
                response.setErrmsg("微信API调用失败：" + result);
                return ResponseEntity.badRequest().body(response);
            }
        } catch (WxErrorException e) {
            // 返回微信错误响应
            DraftResponse response = new DraftResponse();
            response.setErrcode(e.getError().getErrorCode());
            response.setErrmsg(e.getError().getErrorMsg());
            return ResponseEntity.badRequest().body(response);
        } catch (Exception e) {
            // 返回系统错误
            DraftResponse response = new DraftResponse();
            response.setErrcode(-1);
            response.setErrmsg("系统错误：" + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    // 提取media_id的辅助方法
    private String extractMediaId(String result) {
        try {
            // 简单的JSON解析，提取media_id
            if (result.contains("media_id")) {
                int start = result.indexOf("media_id") + 11;
                int end = result.indexOf("\"", start);
                return result.substring(start, end);
            }
            return "unknown_media_id";
        } catch (Exception e) {
            return "extract_error_" + System.currentTimeMillis();
        }
    }

    // 接收请求的DTO类 - 映射Coze发送的JSON参数
    @Data
    public static class DraftRequest {
        private List<DraftArticle> articles;
    }

    // 文章内容DTO类
    @Data
    public static class DraftArticle {
        private String article_type = "news"; // 默认图文类型
        private String title;
        private String author;
        private String digest;
        private String content;
        private String content_source_url;
        private String thumb_media_id;
        private Integer need_open_comment = 0;
        private Integer only_fans_can_comment = 0;
        private String pic_crop_235_1;
        private String pic_crop_1_1;
        private ImageInfo image_info;
        private CoverInfo cover_info;
        private ProductInfo product_info;
    }

    // 图片信息DTO类
    @Data
    public static class ImageInfo {
        private List<ImageItem> image_list;
    }

    @Data
    public static class ImageItem {
        private String image_media_id;
    }

    // 封面信息DTO类
    @Data
    public static class CoverInfo {
        private List<CropPercent> crop_percent_list;
    }

    @Data
    public static class CropPercent {
        private String ratio;
        private String x1;
        private String y1;
        private String x2;
        private String y2;
    }

    // 商品信息DTO类
    @Data
    public static class ProductInfo {
        private FooterProductInfo footer_product_info;
    }

    @Data
    public static class FooterProductInfo {
        private String product_key;
    }

    // 草稿响应DTO类
    @Data
    public static class DraftResponse {
        private String media_id;
        private Integer errcode;
        private String errmsg;
    }

    // 素材上传响应DTO类
    @Data
    public static class MaterialResponse {
        private String media_id;
        private String url;
        private Integer errcode;
        private String errmsg;
    }
}